package com.pn.service.impl;

import com.pn.entity.Product;
import com.pn.entity.Result;
import com.pn.page.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.pn.mapper.ProductMapper;
import com.pn.service.ProductService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Value("${file.access-path}")
    private String fileAccessPath;
    @Resource
    private ProductMapper productMapper;

    @Override
    public Page queryProductPage(Page page, Product product) {

        // 查询商品
        List<Product> productList = productMapper.selectProductPage(page, product);

        // 查询商品条数
        Integer totalNum = productMapper.selectProductRowCount(product);

        page.setResultList(productList);
        page.setTotalNum(totalNum);
        return page;
    }

    @Override
    public Result addProduct(Product product) {

        // 根据型号查询商品是否存在
        Product info = productMapper.selectProductByNum(product.getProductNum());
        if (info != null) {
            return Result.err(Result.CODE_ERR_BUSINESS, "商品型号已存在！");
        }

        // 拼接图片路径存到数据库
        product.setImgs(fileAccessPath + product.getImgs());
        int result = productMapper.insertProduct(product);

        if (result > 0) {
            return Result.ok("商品添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品添加失败！");
    }

    @Override
    public Result setProductState(Product product) {

        int result = productMapper.updateProductState(product);

        if (result > 0) {
            return Result.ok("商品上下架状态设置成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品上下架状态设置失败！");
    }

    @Override
    public Result removeProductByIds(List<Integer> productIds) {

        int result = productMapper.deleteProductByIds(productIds);

        if (result > 0) {
            return Result.ok("删除商品成功！");
        }

        return Result.err(Result.CODE_ERR_BUSINESS, "删除商品失败！");
    }

    @Override
    public Result setProductById(Product product) {

        Product info = productMapper.selectProductByNum(product.getProductNum());

        if (info != null && !info.getProductId().equals(product.getProductId())) {
            return Result.err(Result.CODE_ERR_BUSINESS, "修改后的型号已存在！");
        }

        // 判断图片是否被修改,如果不包含完整路径，说明图片被修改，拼接路径
        if (!product.getImgs().contains(fileAccessPath)) {
            product.setImgs(fileAccessPath + product.getImgs());
        }

        int result = productMapper.updateProductById(product, product.getProductId());

        if (result > 0) {
            return Result.ok("商品信息修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "商品信息修改失败！");
    }
}
